package org.dandelion.memo.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;

import org.dandelion.R;
import org.dandelion.memo.dao.DBHelper;
import org.dandelion.memo.dao.MemoDao;
import org.dandelion.memo.entity.Memo;
import org.dandelion.memo.entity.MemoCategory;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class AddMemoActivity extends BaseActivity {
    private static final String TAG = "AddMemoActivity";

    private Toolbar toolbar;
    private Button cancelBtn;
    private Button selectDateBtn;
    private Button selectTimeBtn;
    private Button collectBtn;
    private Button saveBtn;

    private TextView dateTimeTv;
    private EditText titleEt;
    private EditText contentEt;

    private Status status;

    private LocalDateTime dateTime = null;
    private LocalDate date = null;
    private LocalTime time = null;
    private Memo memo = null;

    private final MemoDao memoDao = MemoDao.getInstance();
    private DBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_memo);
        findView();
        dbHelper = new DBHelper(this, "toolbox", null, 1);

        initData();
        setSupportActionBar(toolbar);

        updateBottomBtn();
        setButtonListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dbHelper.close();
    }

    private void updateBottomBtn() {
        if (memo.isDeleted()) {
            saveBtn.setEnabled(false);
            selectTimeBtn.setEnabled(false);
            collectBtn.setEnabled(false);
        } else {
            saveBtn.setEnabled(true);
            selectTimeBtn.setEnabled(true);
            collectBtn.setEnabled(true);

            if (memo.isFavourite()) {
                collectBtn.setText("取消收藏");
            } else {
                collectBtn.setText("收藏");
            }
        }
    }

    private void initData() {
        Intent intent = getIntent();
        Object obj = intent.getSerializableExtra("memo");

        if (obj != null) {
            status = Status.EDIT;
            memo = (Memo) obj;
            dateTime = memo.getDateTime();
            date = dateTime.toLocalDate();
            time = dateTime.toLocalTime();
            titleEt.setText(memo.getTitle());
            contentEt.setText(memo.getContent());
            dateTimeTv.setText(memo.getDateTimeAsString());
        } else {
            status = Status.NEW;
            memo = new Memo();
            memo.setCategory(new MemoCategory());
            dateTimeTv.setText("");
        }
    }

    private void getCurrentDateTime() {
        dateTime = LocalDateTime.now();
        date = dateTime.toLocalDate();
        time = dateTime.toLocalTime();
    }

    private void findView() {
        toolbar = findViewById(R.id.toolbar);
        cancelBtn = findViewById(R.id.btn_cancel);
        selectDateBtn = findViewById(R.id.btn_select_date);
        selectTimeBtn = findViewById(R.id.btn_select_time);
        saveBtn = findViewById(R.id.btn_save);
        collectBtn = findViewById(R.id.btn_collect);
        titleEt = findViewById(R.id.et_title);
        contentEt = findViewById(R.id.et_content);
        dateTimeTv = findViewById(R.id.tv_datetime);
    }

    private void setButtonListener() {
        cancelBtn.setOnClickListener(view -> finish());

        selectDateBtn.setOnClickListener(view -> selectDate());

        selectTimeBtn.setOnClickListener(view -> selectTime());

        saveBtn.setOnClickListener(view -> {
            getMemoInfo();
            if (status == Status.NEW) {
                getCurrentDateTime();
                memo.setDateTime(dateTime);
                saveMemo();
                status = Status.EDIT;
            } else {
                updateMemo();
                memo.setDateTime(dateTime);
            }

            updateBottomBtn();

            finish();
        });

        collectBtn.setOnClickListener(view -> {
            getMemoInfo();

            if (status == Status.NEW) {
                memo.setDateTime(LocalDateTime.now());
                memo.setFavourite(true);
                saveMemo();
                status = Status.EDIT;
            } else {
                memo.setFavourite(!memo.isFavourite());
                updateMemo();
            }

            updateBottomBtn();
        });
    }

    private void selectDate() {
        if (dateTime == null) {
            getCurrentDateTime();
        }

        new DatePickerDialog(this, (view, year, month, dayOfMonth) -> {
            date = LocalDate.of(year, month, dayOfMonth);
            dateTime = LocalDateTime.of(date, time);
            memo.setDateTime(dateTime);
            updateDateTime();
        }, dateTime.getYear(), dateTime.getMonthValue(), dateTime.getDayOfMonth()).show();
    }

    private void selectTime() {
        if (dateTime == null) {
            getCurrentDateTime();
        }

        new TimePickerDialog(this, (view, hourOfDay, minute) -> {
            time = LocalTime.of(hourOfDay, minute);
            dateTime = LocalDateTime.of(date, time);
            memo.setDateTime(dateTime);
            updateDateTime();
        }, time.getHour(), time.getMinute(), true).show();
    }

    private void getMemoInfo() {
        String title = titleEt.getText().toString();

        if (title.trim().equals("")) {
            new AlertDialog.Builder(this).setTitle("标题不能为空").show();
        } else {
            memo.setDateTime(dateTime);
            memo.setTitle(title);
            memo.setContent(contentEt.getText().toString());
        }
    }

    private void saveMemo() {
        memoDao.save(memo, dbHelper.getWritableDatabase());
    }

    private void updateMemo() {
        memoDao.update(memo, dbHelper.getWritableDatabase());
    }

    private void updateDateTime() {
        dateTimeTv.setText(memo.getDateTimeAsString());
    }

    enum Status {
        EDIT,
        NEW
    }
}